<?php

class GoodsController extends Controller
{
	public function actionShow()
	{
		$criteria = new CDbCriteria();
		$criteria->order = 'goods_id desc';
		$criteria->with = array('category','brand');
		$count = Goods::model()->count($criteria);
		
		$pages = new CPagination($count);
		$pages->pageSize = 1;
		$criteria->limit = $pages->pageSize;
        $criteria->offset = $pages->currentPage * $pages->pageSize;
		
		$goods_list = Goods::model()->findAll($criteria);
		$this->renderPartial('show',array('goods_list'=>$goods_list,'pages'=>$pages));
	}
	
	public function actionAdd(){
		
		$model = new Goods();
		
		if(isset($_POST['Goods'])){
			
			$model->attributes = $_POST['Goods'];
			
			$file = XUpload::upload( $_FILES['goods_thumb'], array( 'thumb'=>true, 'thumbSize'=>array ( 400 , 250 ) ) );
			if ( is_array( $file ) ) {
				$model->goods_img = $file['pathname'];
				$model->goods_thumb = $file['paththumbname'];
			}
			
			if($model->save()){
				$this->redirect(array('goods/show'));
				
			}
		}
		
		$cat = Category::model()->findAllBySql('select cat_id,cat_name from cz_category');
		$brand = Brand::model()->findAllBySql('select brand_id,brand_name from cz_brand');
		foreach ($cat as $item){
			$cat_list[$item->cat_id]=$item->cat_name;
		}
		foreach ($brand as $item){
			$brand_list[$item->brand_id]=$item->brand_name;
		}
		
		$this->renderPartial('add',array('model'=>$model,'cat_list'=>$cat_list,'brand_list'=>$brand_list));
	}
	
	public function actionUpdate($id){		
		
		$goods_list = Goods::model()->with(array('category','brand'))->findAllByPk($id);
		
		$model = $goods_list[0];
		if(isset($_POST['goods'])){
			
		}
		$cat = Category::model()->findAllBySql('select cat_id,cat_name from cz_category');
		$brand = Brand::model()->findAllBySql('select brand_id,brand_name from cz_brand');
		foreach ($cat as $item){
			$cat_list[$item->cat_id]=$item->cat_name;
		}
		foreach ($brand as $item){
			$brand_list[$item->brand_id]=$item->brand_name;
		}

		$this->renderPartial('update',array('model'=>$model,'cat_list'=>$cat_list,'brand_list'=>$brand_list,'goods_list'=>$goods_list));
	}
}